<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

use App\User;
use Namshi\JOSE\SimpleJWS;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Boot the authentication services for the application.
     *
     * @return void
     */
    public function boot()
    {
        // Here you may define how you wish users to be authenticated for your Lumen
        // application. The callback which receives the incoming request instance
        // should return either a User instance or null. You're free to obtain
        // the User instance via an API token or any other method necessary.

//        $this->app['auth']->viaRequest('api', function ($request) {
//            if ($request->input('api_token')) {
//                return User::where('api_token', $request->input('api_token'))->first();
//            }
//        });



        $this->app['auth']->viaRequest('api', function ($request) {
            //$this->app['auth']->viaRequest('token', function ($request) {


            $token = $request->bearerToken();

            if($token == null) {

                $url = $request->fullUrl();
                Log::info('AuthServiceProvider: (token == null) from url '.$url);

                return null;
            }

            try {

                $jws = SimpleJWS::load($token);
                //Exception

            } catch(\Exception $e) {

                $url = $request->fullUrl();
                Log::info('AuthServiceProvider: token '.$token.' ; url '.$url);
                Log::error($e->getMessage());

                return null;

            }


            $secretKey = env('JWT_KEY');

            if (!$jws->isValid($secretKey, 'HS256')) {

                Log::info('api token is not valid: ' . $token);

                return null;
            }

            //
            $payload = $jws->getPayload();

            //todo: payload , expire time ...

            $uid = $payload['uid'];

            $user = User::find($uid);

            return $user;

        });



    }
}
